package com.uaf.aes.advice;

import com.uaf.aes.utils.AESUtilsDemo;
import com.uaf.aes.utils.FileStreamUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

/**
 * @author cailu
 * @filename MyHttpInputMessage
 * @description
 * @date 2020/5/6 15:13
 */
public class MyHttpInputMessage implements HttpInputMessage {

	private static String PATH = "D:\\uaren\\aeskey\\aes.txt";

	private HttpHeaders headers;

	private InputStream body;

	/**
	 * 功能描述  解密
	 * @param inputMessage HTTP
	 * @author cailu
	 * @date 2020/5/6 15:37
	 */
	public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
		this.headers = inputMessage.getHeaders();

		String data = easpString(IOUtils.toString(inputMessage.getBody(), "UTF-8"));
		data = URLDecoder.decode(data, "utf-8");
		//获取秘钥
		String codeKey = FileStreamUtils.readToString(PATH);
		//解密
		this.body = IOUtils.toInputStream(AESUtilsDemo.decrypt(data, codeKey), "UTF-8");
	}


	@Override
	public InputStream getBody() throws IOException {
		return body;
	}

	@Override
	public HttpHeaders getHeaders() {
		return headers;
	}

	/**
	 * 功能描述  自定义数据处理 对特殊字段或者特殊请求做特殊处理
	 * @param requestData 内容
	 * @return java.lang.String
	 * @author cailu
	 * @date 2020/5/6 15:16
	 */
	public String easpString(String requestData) {
		if (requestData != null && !requestData.equals("")) {
			return requestData;
		}
		return "";
	}
}
